package com.zxl.listener;

import com.rabbitmq.client.Channel;
import com.zxl.constants.MQConstants;
import com.zxl.service.GoodsService;
import com.zxl.vo.Goods;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @packageName com.zxl.listener
 * @ClassName
 * @Author zxl
 * @Description //TODO
 * @date
 **/
@Component
public class MQListener {
    @Autowired
    private GoodsService goodsService;

    @RabbitListener(queues = MQConstants.ITEM_ADD_QUEUE)
    public void addItem(Goods goods, Channel channel, Message message) throws IOException {

        try {
            String routingKey = message.getMessageProperties().getReceivedRoutingKey();
            if (routingKey != null) {
                switch (routingKey) {
                    case "goods.add":
                        goodsService.add(goods);
                        break;
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }

    }

}
